package com.azure.code.dfs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class NQueen_51 {
    List<List<String>> res = new LinkedList<>();
    public List<List<String>> solveNQueens(int n) {
        char[][] board = board(n);
        backTrack(board,0);
        return res;
    }

    public static void main(String[] args) {
        List<List<String>> lists = new NQueen_51().solveNQueens(4);
        lists.forEach(o->{
            System.out.println(o);
            o.forEach(System.out::println);
            System.out.println("");
        });
    }

    private void backTrack(char[][] board, int row) {
        // 触发结束条件
        if(row == board.length) {
            res.add(charToList(board));
            return;
        }
        int n = board[row].length;
        for(int col = 0; col < n; col++){
            // 排除不合法的选择
            if(!isValid(board,row,col)){
                continue;
            }
            // 做选择
            board[row][col] = 'Q';
            // 进入下一行决策
            backTrack(board,row+1);
            board[row][col] = '.';
        }
    }

    private boolean isValid(char[][] board, int row, int col) {
        int n = board.length;

        // 检查列是否有皇后相互冲突
        for (int i = 0; i <= row; i++) {
            if(board[i][col] == 'Q'){
                return false;
            }
        }
        // 检查右上方是否有皇后互相冲突
        for (int i = row-1,j=col+1; i >= 0&&j<n ; i--,j++) {
            if(board[i][col] == 'Q'){
                return false;
            }
        }
        // 检查左上方是否有皇后互相冲突
        for (int i = row-1,j = col-1; i >=0 && j>=0 ; i--,j--) {
            if(board[i][j]=='Q'){
                return false;
            }
        }
        return true;
    }

    private List<String> charToList(char[][] board) {
        List<String> list = new ArrayList<>();
        for (char[] c : board) {
            list.add(String.valueOf(c));
        }
        return list;
    }

    private char[][] board(int n) {
        char[][] board = new char[n][n];
        for (char[] chars : board) {
            Arrays.fill(chars,'.');
        }
        return board;
    }
}
